<template>
  <div class="header-with-back">
    <div class="back-nav" @click="goToLogin">
      <van-icon name="arrow-left" />
      <span style="font-size: 1.2rem">返回登录</span>
    </div>
  </div>

  <div class="fw">
  </div>

  <div class="auth-box">
    <h2>找回密码</h2>
    <van-cell-group inset style="margin-bottom: 10px">
      <van-field
          v-model="resetForm.userNumber"
          name="工号"
          label="工&nbsp;&nbsp;&nbsp;&nbsp;号"
          placeholder="请输入工号"
          label-align="left"
          :rules="[{ required: true, message: '请填写工号' }]"
          size="large"
      />
      <van-field
          v-model="resetForm.email"
          name="邮箱"
          label="邮&nbsp;&nbsp;&nbsp;&nbsp;箱"
          placeholder="请输入邮箱"
          label-align="left"
          :rules="[{ required: true, message: '请填写邮箱' }]"
          size="large"
      />
        <van-field
            v-model="resetForm.verificationCode"
            center
            clearable
            label="验证码"
            placeholder="验证码"
            :rules="[{ required: true, message: '请输入邮箱' }]"
            size="large"
        >
          <template #button>
            <van-button
                size="small"
                type="primary"
                @click="sendVerificationCode"
                :disabled="resetForm.countdown > 0 || !isValidEmail(resetForm.email)"
            >
              {{ resetForm.countdown > 0 ? `${resetForm.countdown}秒` : '获取验证码' }}
            </van-button>
          </template>
        </van-field>
      <van-field
          v-model="resetForm.newPassword"
          label="新密码"
          name="新密码"
          placeholder="请输入新密码"
          label-align="left"
          type="password"
          :rules="[{ required: true, message: '请再次输入密码' }]"
          size="large"
      />
      <van-field
          v-model="resetForm.confirmPassword"
          label="确认密码"
          name="确认密码"
          placeholder="请再次输入新密码"
          label-align="left"
          type="password"
          :rules="[{ required: true, message: '请再次输入密码' }]"
          size="large"
      />
      </van-cell-group>

    <van-checkbox
        v-model="resetForm.checked"
        checked-color="#ee0a24"
        icon-size="small"
    >
      点击阅读并同意
      <span class="link-text" @click="showBusinessAgreement">《业务开展协议》</span>
      和
      <span class="link-text" @click="showPrivacyAgreement">《隐私协议》</span>
    </van-checkbox>

    <div class="button-container">
      <van-button
          :loading="resetForm.loading"
          :disabled="isResetDisabled"
          type="primary"
          @click="handleReset"
      >重置密码</van-button>
    </div>
    </div>
</template>


<script setup lang="ts" name="LoginView">

import { showDialog, showToast } from 'vant';
import { useRouter } from 'vue-router';
import {useLoginStore} from "../../Store/modules/userinfo/LoginTZ";
import { agreements, AgreementType } from '../../Constants/agreements';
import {resetPasswordUsingPost, sendResetCodeUsingPost, verifyResetCodeUsingPost} from "../../Api/yonghumokuai";
import {computed, reactive} from "vue";


// 使用 store
const RegisterStore = useLoginStore();
//切换到登陆页面
const goToLogin = () => {
  RegisterStore.setActiveTab('login');
  // console.log(RegisterStore.activeTab)
};

const router = useRouter();

// 重置密码表单
const resetForm = reactive({
  userNumber: '',
  email: '',
  verificationCode: '',
  newPassword: '',
  confirmPassword: '',
  loading: false,
  countdown: 0,
  checked: false
});

// 验证邮箱格式
const isValidEmail = (email: string) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
};

// 按钮禁用状态
const isResetDisabled = computed(() => {
  return !resetForm.userNumber ||
      !resetForm.email ||
      !resetForm.verificationCode ||
      !resetForm.newPassword ||
      !resetForm.confirmPassword ||
      !resetForm.checked;
});

// 增加协议安全类型检查
const showBusinessAgreement = () => showAgreement('business');
const showPrivacyAgreement = () => showAgreement('privacy');

// 显示协议
function showAgreement(type: AgreementType) {
  const agreement = agreements[type];
  showDialog({
    title: agreement.title,
    message: agreement.content,
    confirmButtonText: '我已阅读'
  });
}

// 发送验证码
async function sendVerificationCode() {
  if (!isValidEmail(resetForm.email)) {
    showToast('请输入正确的邮箱格式');
    return;
  }
  try {
    const response = await sendResetCodeUsingPost({
      email: resetForm.email
    })
    const data = response.data
    if (data.code === 0) {
      showToast('验证码已发送');
      resetForm.countdown = 60;
      const timer = setInterval(() => {
        resetForm.countdown--;
        if (resetForm.countdown <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    } else {
      showToast(data.message || '验证码发送失败');
    }
  } catch (error: any) {
    showToast(error.response?.data?.message || '验证码发送失败');
  }
}

// 重置密码处理
async function handleReset() {
  if (!resetForm.checked) {
    showDialog({
      message: '请同意用户协议和隐私协议',
    });
    return;
  }

  if (resetForm.newPassword !== resetForm.confirmPassword) {
    showToast('两次输入的密码不一致');
    return;
  }

  if (resetForm.newPassword.length < 8) {
    showToast('密码长度不能小于8位');
    return;
  }

  resetForm.loading = true;
  try {
    const response = await resetPasswordUsingPost({
      code: resetForm.verificationCode,
      email: resetForm.email,
      password: resetForm.newPassword
    })
    const data = response.data
    if (data.code === 0) {
      showToast('密码重置成功');
      RegisterStore.setActiveTab('login');
    } else {
      showToast(data.message || '密码重置失败');
    }
  } catch (error: any) {
    showDialog({
      message: error.response?.data?.message || '密码重置失败，请重试',
    });
  } finally {
    resetForm.loading = false;
  }
}
</script>

<style scoped>
/* 第一层盒子样式 */
.auth-box {
  width: 82%;
  margin: 0 auto;
  padding: 15px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
}

/* 撑高盒子的样式 */
.fw {
  height: 17%;
}

/* 注册标题样式 */
h2 {
  font-size: 170%;
  font-weight: 400;
  margin: 15px 15px;
  color: #9a009a;
}

/*表单输入框长度*/
:deep(.van-cell) {
  width: 100%;
}

/* 链接文本的样式 */
.link-text {
  color: #747bff;
  cursor: pointer;
  display: inline-block;
  margin: 0 auto;
  transition: all 0.2s ease;;
}

.link-text:hover {
  opacity: 0.8;
  color: #7c2d7c;
  text-decoration: none;
}

/*按钮*/
.button-container {
  margin: 10px auto;
  width: 90%;
}

/* 下拉框基础样式 */
:deep(.van-dropdown-menu) {
  display: flex;
  max-height: 20%;
  margin-left: 3%;
  width: auto !important;
}

/* 下拉框初始样式 */
:deep(.van-dropdown-item) {
  max-width: 74%;
  max-height: 20%;
  margin-left: 13%;
  width: auto !important;
}

/*下拉框伸展展示底部样式*/
:deep(.van-overlay) {
  width: 30% !important;
  height: 30% !important;
}

/*菜单未展开样式*/
:deep(.van-dropdown-menu__bar, .van-dropdown-menu__bar--opened) {
  background-color: rgb(253, 253, 254) !important;
  box-shadow: none !important;
}

/* 下拉框伸展样式 */
:deep(.van-dropdown-item--down) {
  background-color: white !important;
}

/* 主按钮样式 */
:deep(.van-button--primary) {
  width: 100%;
  background-color: #800080;
  border: none;
}

/* 主按钮非禁用状态下的样式 */
:deep(.van-button--primary:not(:disabled)) {
  background-color: #800080;
}

/* 主按钮非禁用状态下的悬停效果 */
:deep(.van-button--primary:not(:disabled):hover) {
  background-color: #9a009a;
}

/* 主按钮禁用状态下的样式 */
:deep(.van-button--primary:disabled) {
  background-color: #cccccc;
  opacity: 0.6;
}

.header-with-back {
  height: 40px;
  padding: 10px;
  text-align: left;
  font-size: 20px;
  color: #682757;
  line-height: 40px;
  overflow: hidden;
  min-width: 100%;
  position: fixed;
  z-index: 999;
}

.back-nav {
  position: fixed;
  left: 1%;
  top: 1.25%;
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  color: rgb(83, 30, 88);
  padding: 0.5rem;
  z-index: 10;
  font-size: 0.9rem;
}

.header-with-back .van-icon {
  position: static;
  font-size: 1.35rem;
}

/*复选框基础*/
:deep(.van-checkbox) {
  margin-left: 15px;
  font-size: 10%;
  padding-top: 2%;
  padding-bottom: 2%;
}

</style>



